package com.jia.jwt.controller;


import com.jia.jwt.entity.User;
import com.jia.jwt.entity.vo.LoginVo;
import com.jia.jwt.service.UserService;
import com.jia.jwt.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dujiajia
 * @since 2021-01-28
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("/login")
    public Map<String,Object> login(@RequestBody LoginVo user) {
        HashMap<String, Object> map = new HashMap<>();

        try {
            User loginUser = userService.login(user);
            String id = loginUser.getId() + "";
            String username = loginUser.getUsername();
            HashMap<String, String> payload = new HashMap<>();
            payload.put("id",id);
            payload.put("username",username);
            String token = JWTUtil.createToken(payload);

            map.put("token",token);
            map.put("code",200);
            map.put("msg","登录成功");

        }catch (Exception e){
            map.put("code",400);
            map.put("msg",e.getMessage());
        }

        return map;
    }

    @GetMapping("/list")
    public List<User> list() {
        return  userService.list();
    }

    @GetMapping("/info/{id}")
    public User info(@PathVariable("id") Long id){
        User user = userService.getUserById(id);
        return user;
    }

}

